package com.foo.Servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.foo.DataProvider.ProviderClient;
import com.foo.DataReciever.DataReciever;
import com.foo.Entity.RealTimeData;
import com.foo.Writer.WriterClient;
import com.foo.Constants.Constants;
import com.foo.Constants.UIMessages;

/**
 * Servlet implementation class AnalysisDataServelet
 */
public class AnalyzedServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	RealTimeData[] tickerdata =null;
	String[] trialstring = null;
	String fileName;
	WriterClient writer = new WriterClient();

	//int j =0;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AnalyzedServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		HttpSession session = request.getSession(true);
		boolean downloadRequired = false;
		boolean readDatabase = false;
		String filetype = "";
		try
		{
			String exampleName = request.getParameter("SortBased");
			System.out.println("the param " +exampleName);
						
			if(request.getParameter("TXT.x") != null)
			{
				filetype ="TXT";
				downloadRequired = true;
			}
			else if(request.getParameter("CSV.x")!= null)
			{
				filetype ="CSV";
				downloadRequired = true;
			}
			else if(request.getParameter("JSON.x")!= null)
			{
				filetype ="JSON";
				downloadRequired = true;
			}		
			else if(request.getParameter("XML.x")!= null)
			{
				filetype ="XML";
				downloadRequired = true;
			}
		
			if(downloadRequired)
			{
				RealTimeData[] sessionData = (RealTimeData[])session.getAttribute("AnalyzedData");
				if(sessionData == null)
				{
					readDatabase = true;
				}
			}
			else
			{
				readDatabase = true;
			}
			if(readDatabase)
			{
				DataReciever receive = new DataReciever();
					
				//not included date since logic of writing data was not discussed
				ProviderClient client = new ProviderClient();
		   	 	client.getData(exampleName,null,null,null,null);
				
				trialstring = receive.readtickerinfodata();
				if(trialstring != null)
				{
					System.out.println("values length: " +trialstring.length);
					int tickerlength = trialstring.length/7;
					tickerdata = new RealTimeData[tickerlength];
					int j =0;
					string_to_object(trialstring,tickerlength);		
				}
				else
				{
					System.out.println("No message returned");
				}
				System.out.println("Exited Loop");
				if(tickerdata != null)
				{
					session.setAttribute("AnalyzedData", tickerdata);
					session.setAttribute("AnalyzedDataString",trialstring);
					RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/analysed.jsp");
					dispatcher.forward(request, response);
				}
				else
				{
					request.setAttribute("ServerMessage", UIMessages.NO_RECORD);
					RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/analysed.jsp");
					dispatcher.forward(request, response);
				}
			}
			else if(downloadRequired)
			{
				
				if(trialstring ==null || trialstring.length == 0)
				{
					trialstring = (String[])session.getAttribute("AnalyzedDataString");
				}
				if(trialstring!=null && trialstring[0] != "" && filetype !=null)
				{
					if(filetype.equals("CSV"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						//CSVWriterClient client = new CSVWriterClient();
						fileName =Constants.FILE_PATH + "data.csv";
						//client.generateCSV(fileName, trialstring,"Analyzed");
						writer.selectfile(fileName, trialstring,"Analyzed");
						System.out.println("File Generate and stored in workspace folder: ");
						
						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
						response = downloadData(response,fileName);
						
						RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/analysed.jsp");
						dispatcher.forward(request, response);
						System.out.println("File Generate and stored in workspace folder: ");
					}
					else if(filetype.equals("TXT"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						//CSVWriterClient client = new CSVWriterClient();
						
						fileName =Constants.FILE_PATH + "data.txt";
						//client.generateCSV(fileName, trialstring,"Analyzed");
						writer.selectfile(fileName, trialstring,"Analyzed");

						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
						response = downloadData(response,fileName);
						
						RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/analysed.jsp");
						dispatcher.forward(request, response);
						System.out.println("File Generate and stored in workspace folder: ");
					}
					else if(filetype.equals("JSON"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						//JSONWriterClient client = new JSONWriterClient();
						fileName =Constants.FILE_PATH + "data.json";
						//client.generateJSON(fileName, trialstring,"Analyzed");
						writer.selectfile(fileName, trialstring,"Analyzed");

						System.out.println("File Generate and stored in workspace folder: ");
						
						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
						response = downloadData(response,fileName);
						
						RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/analysed.jsp");
						dispatcher.forward(request, response);
						System.out.println("File Generate and stored in workspace folder: ");
					}
					else if(filetype.equals("XML"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						//XMLWriterClient client = new XMLWriterClient();
						fileName =Constants.FILE_PATH + "data.xml";
						//client.generateJSON(fileName, trialstring,"Analyzed");
						writer.selectfile(fileName, trialstring,"Analyzed");

						System.out.println("File Generate and stored in workspace folder: ");
						
						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
						response = downloadData(response,fileName);
						
						RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/analysed.jsp");
						dispatcher.forward(request, response);
						System.out.println("File Generate and stored in workspace folder: ");
					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			request.setAttribute("ServerMessage", UIMessages.SERVICE_UNAVAILABLE);
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/analysed.jsp");
			dispatcher.forward(request, response);
		}
	}
	public HttpServletResponse downloadData(HttpServletResponse response,String fileName) throws Exception
	{
		try
		{
			if(new File(fileName).exists())
			{
				File fileContent = new File(fileName);
				InputStream inputStream = new FileInputStream(fileContent);
				long length = fileContent.length();
				
			 if (length > Integer.MAX_VALUE) {
			        // File is too large
			    }
			 response.reset();
				response.setContentType("application/file");
				String name = new File(fileName).getName();
				System.out.println("File Name is :" + name);
				response.setHeader("Content-disposition","attachment; filename=" +name);
				   
			    byte[] bytes = new byte[(int)length];
	
			    int offset = 0,numRead = 0;
			    while (offset < bytes.length
			           && (numRead=inputStream.read(bytes, offset, bytes.length-offset)) >= 0) {
			        offset += numRead;
			        response.getOutputStream().write(bytes, 0, numRead);
			    }
	
			    if (offset < bytes.length) {
			        throw new IOException("Could not completely read file data.txt");
			    }
	
			    inputStream.close();
			}
			response.getOutputStream().flush();
			return response;
		}
		catch(Exception e)
		{
			throw e;
		}
	}
	public void string_to_object(String[] trialstring, int tickerarraysize) throws Exception
	{
		try
		{
			int j=0;
			tickerdata = new RealTimeData[tickerarraysize];

				for(int i =0;i<trialstring.length;i+=7)
				{
					RealTimeData ticker=new RealTimeData();
					if(trialstring[i].equals("") || trialstring[i] == null)
					{
						System.out.println("No more data to print");
						break;
					}
					else
					{
					ticker.setTicker_symbol(trialstring[i]);
					ticker.setOpen_value(Double.parseDouble(trialstring[i+1]));
					ticker.setHigh_value(Double.parseDouble(trialstring[i+2]));
					ticker.setLow_value(Double.parseDouble(trialstring[i+3]));
					ticker.setClose_value(Double.parseDouble(trialstring[i+4]));
					ticker.setVolume(Long.parseLong(trialstring[i+5]));
					ticker.setPerc_change(Double.parseDouble(trialstring[i+6]));
					tickerdata[j]=ticker;		
					j=j+1;
					}
				}
			System.out.println("Conversion to objectdata was successful");			
		}
		catch(Exception e)
		{
			throw e;
		}
	}

}
